package com.ruoyi.common.utils.ping;

import com.jcraft.jsch.*;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class RemotePortScannerSSH {

    public static void main(String[] args) {
        String host = "10.61.102.115";
        String user = "root";
        String password = "ZDyw#@1108";
        int SSH_port = 17122;

        List<Integer> usedPorts = getUsedPorts(host, user, password,SSH_port);

        System.out.println("Used ports on " + host + ": " + usedPorts);
    }

    public static List<Integer> getUsedPorts(String host, String user, String password,int SSH_port) {
        List<Integer> usedPorts = new ArrayList<>();

        try {
            JSch jsch = new JSch();
            Session session = jsch.getSession(user, host, SSH_port);
            session.setConfig("StrictHostKeyChecking", "no");
            session.setPassword(password);
            session.connect();

            String command = "netstat -tln | grep 'LISTEN' | awk '{print $4}' | awk -F: '{print $NF}'";
            Channel channel = session.openChannel("exec");
            ((ChannelExec) channel).setCommand(command);

            channel.setInputStream(null);
            ((ChannelExec) channel).setErrStream(System.err);

            InputStream in = channel.getInputStream();
            channel.connect();

            BufferedReader reader = new BufferedReader(new InputStreamReader(in));
            String line;
            while ((line = reader.readLine()) != null) {
                int port = Integer.parseInt(line.trim());
                usedPorts.add(port);
            }
            //端口排序
            Collections.sort(usedPorts);

            channel.disconnect();
            session.disconnect();

        } catch (JSchException | IOException e) {
            e.printStackTrace();
        }

        return usedPorts;
    }
}
